/**
 *  filename:   iterative_server.c
 *  author:     大梦
 *  date:       2015/4/9
 *  desc:       linux时间服务器，迭代服务器
 *  history:
 *              2015/4/9 create the file
 */

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/select.h>
#include <errno.h>
#include <time.h>

#define MAXLINE 1024

void time_busi(int connfd)
{
    time_t ticks;
    int left_bytes;
    int written_bytes;
    char buff[MAXLINE];
    char *ptr;

    ticks = time(NULL);
    snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));

    left_bytes = strlen(buff);
    ptr = buff;

    while (left_bytes > 0)
    {
        written_bytes = write(connfd, ptr, left_bytes);
        if (written_bytes < 0)
        {
            if (errno == EINTR)
                written_bytes = 0;
        }
        left_bytes -= written_bytes;
        ptr += written_bytes;
    }
}

int main()
{
    int listenfd, connfd;
    struct sockaddr_in servaddr;

    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if (listenfd == -1)
    {
        perror("socket error.");
        return -1;
    }

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(10889);

    if (-1 == bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)))
    {
        perror("bind error.");
        return -1;
    }

    if (-1 == listen(listenfd, 50))
    {
        perror("listen error.");
        return -1;
    }

    for (;;)
    {
        connfd = accept(listenfd, (struct sockaddr *)NULL, NULL);
        if (-1 == connfd)
        {
            perror("accept error.");
            return -1;
        }
        printf("new connection.\n");
        time_busi(connfd);
        if (-1 == close(connfd))
        {
            perror("close error.");
            return -1;
        }
    }

    return 0;
}
